package zdream.control.region;

import zdream.utils.math.Point2d;

import java.util.*;

import static org.junit.Assert.*;
import static zdream.control.region.TerrainConstant.*;

/**
 * @author Zdream
 * @date 2023-12-25
 * @since 0.0.1
 */
public class SimpleRoomBuilder {
	private final SimpleRegionBuilder parent;
	private final Room room;
	private int y;

	public SimpleRoomBuilder(SimpleRegionBuilder parent, Room room) {
		this.parent = Objects.requireNonNull(parent);
		this.room = Objects.requireNonNull(room);

		this.y = room.height - 1;
	}

	public SimpleRoomBuilder defineTerrain(char ch, byte terrain) {
		parent.defineTerrain(ch, terrain);
		return this;
	}

	public SimpleRoomBuilder terrain(String text) {
		assertEquals("这个房间长度是 " + room.width + ", 所以你必须传入一个这么长的地形数据",
				room.width, text.length());
		assertTrue("你已经放入了足够多的地形数据", y >= 0);
		parseTerrainLine(text.toCharArray(), y);
		y--;
		return this;
	}

	public SimpleRegionBuilder build() {
		return this.parent;
	}

	private void parseTerrainLine(char[] text, int y) {
		final byte[][] terrains = room.terrains;
		Map<Character, Byte> terrainMap = parent.terrainMap;
		Map<Character, List<Point2d>> points = parent.points;

		for (int x = 0; x < text.length; x++) {
			char c = text[x];
			byte terrain = terrainMap.getOrDefault(c, TERRAIN_EMPTY);
			terrains[x][y] = terrain;

			if (points.containsKey(c)) {
				points.get(c).add(new Point2d(x, y));
				continue;
			}
			if (!terrainMap.containsKey(c)) {
				List<Point2d> list = new ArrayList<>();
				list.add(new Point2d(x, y));
				points.put(c, list);
			}
		}
	}
}
